package com.freewater.cargotracker.infrastructure.persistence.mybatis.converter;

import com.freewater.cargotracker.domain.model.voyage.CarrierMovement;
import com.freewater.cargotracker.domain.model.voyage.Schedule;
import com.freewater.cargotracker.domain.model.voyage.Voyage;
import com.freewater.cargotracker.domain.model.voyage.VoyageNumber;
import com.freewater.cargotracker.infrastructure.persistence.mybatis.dbobject.CarrierMovementPO;
import com.freewater.cargotracker.infrastructure.persistence.mybatis.dbobject.VoyagePO;

import java.util.List;
import java.util.stream.Collectors;

public class VoyageConverter {

    public static VoyagePO serialize(Voyage voyage) {
        if (voyage == null) {
            return null;
        }
        VoyagePO po = new VoyagePO();
        final Long voyageId = voyage.getId();
        po.setId(voyageId);
        po.setNumber(voyage.getVoyageNumber().getIdString());
        po.setDescription(voyage.getDescription());
        po.setCapacity(voyage.getCapacity());
        po.setVersion(voyage.getVersion());
        final List<CarrierMovement> carrierMovements = voyage.getSchedule().getCarrierMovements();
        final List<CarrierMovementPO> carrierMovementPOs = carrierMovements.stream()
                .map(movement -> CarrierMovementConverter.serialize(voyageId, movement))
                .collect(Collectors.toList());
        po.setCarrierMovements(carrierMovementPOs);
        return po;
    }

    public static Voyage deserialize(VoyagePO voyagePO) {
        if (voyagePO == null) {
            return null;
        }
        final String number = voyagePO.getNumber();
        final List<CarrierMovement> carrierMovements = voyagePO.getCarrierMovements().stream()
                .map(CarrierMovementConverter::deserialize).collect(Collectors.toList());
        Voyage voyage = new Voyage(new VoyageNumber(number), new Schedule(carrierMovements));
        voyage.setDescription(voyagePO.getDescription());
        voyage.setCapacity(voyagePO.getCapacity());
        voyage.setId(voyagePO.getId());
        voyage.setVersion(voyagePO.getVersion());
        return voyage;
    }
}
